#include <func.h>
#include"log.h"
#include"mySql.h"
#include"project.h"
#include"threadpool.h"

#define PATH_MLEN 1048         //路径最大长度(mkDir)
//小火车发送
void trainSend(char* buff,int peerfd){
    train_t train;
    train.length = strlen(buff);
    strncpy(train.data,buff,train.length);
    int ret = sendn(peerfd,&train,4+train.length);
    printf("send %d bytes\n",ret);
}
void trainSendPlus(char* buff,int peerfd){
    train_t train;
    train.length = strlen(buff)-1;
    strncpy(train.data,buff,train.length);
    int ret = sendn(peerfd,&train,4+train.length);
    printf("send %d bytes\n",ret);
}

//小火车接收
void trainRecv(char*buff,int peerfd){
    int length;
    int ret = recv(peerfd,&length,4,MSG_WAITALL);
    printf("1---trainRecv length is:%d\n",length);
    ret = recv(peerfd,buff,length,MSG_WAITALL);
    printf("1---trainRecv buff is:%s\n",buff);
}
//命令解析实现
void splitChar(char* from, char* operate, char* operand){
    int fromLen = strlen(from);
    int i = 0, j = 0;

    for(i = 0;i<fromLen;i++){
        if(from[i]==' '){
            i++;
            break;
        }else{
            operate[i] = from[i];
        }
    }
    printf("split order is %s\n",operate);

    for(j=0;i<fromLen;j++,i++){
        operand[j]=from[i];
    }
    printf("split filename is %s\n",operand);

}

//命令判断
int judge(char*order,char*filename,int peerfd,MYSQL*mysql,
          int parent_id,char*username,
          int owner_id){

    //char pwd_3th[1000];//用来记录每次cd指令后当前用户的位置
    //getcwd(pwd_3th,sizeof(pwd_3th));
    //printf}("pwd_3th is:%s\n",pwd_3th);
    //int Psize=0;//记录cd执行后上一次pwd的大小

if(strcmp(order,"rm") == 0){
    //日志记录
    char logbuff[100]={0};
    sprintf(logbuff,"order is :rm! filename is:%s",filename);
    writelog(logbuff);
    printf(">order have rm\n");
    //rm(filename,peerfd);
    rm_3th(mysql,username,filename,parent_id,
           owner_id,peerfd);
}else if(strcmp(order,"cd")== 0){
    //日志记录
    char logbuff[100]={0};
    sprintf(logbuff,"order is :cd! filename is:%s",filename);
    writelog(logbuff);
    //cd(filename,peerfd);
    parent_id = cd_3th(mysql,username,filename,
                       owner_id,parent_id,peerfd);
    printf("parent_id is:%d\n",parent_id);
}

else if(strcmp(order,"pwd")==0){
    //日志记录
    char logbuff[100]={0};
    sprintf(logbuff,"order is :pwd! filename is:%s",filename);
    writelog(logbuff);
    printf("order is pwd\n");
    //pwd(peerfd);
    pwd_3th(mysql,username,parent_id,peerfd);        
}else if(strcmp(order,"puts")==0){
    //日志记录
    char logbuff[100]={0};
    sprintf(logbuff,"order is :puts! filename is:%s",filename);
    writelog(logbuff);

    char md5[100]={0};
    trainRecv(md5,peerfd);
    printf("%s md5:%s\n",filename,md5);
    char size[100]={0};

    trainRecv(size,peerfd);
    int filesize = atoi(size);
    printf("%s filesize:%d\n",filename,filesize);

    //char query[1000]={0};
    //sprintf(query,"select md5 from %s where md5 = '%s';",
    //        username,md5);

    //handlQuery(mysql,query);
    //MYSQL_RES *res;//SQL执行结果
    //MYSQL_ROW row ={0};//保存行数据
    //if((row=mysql_fetch_row(res))!=NULL){
    //    
    //}
    //do_puts(peerfd,filename);
    do_puts_3th(mysql,filename,username,md5,peerfd,
                parent_id,owner_id,filesize);
}/*else if(strcmp(order,"gets")==0){
   trainSend(order,peerfd); 
   do_gets(peerfd,filename);
   }*/else if(strcmp(order,"mkdir")==0){
       //日志记录
       char logbuff[100]={0};
       sprintf(logbuff,"order is :mkdir! filename is:%s",filename);
       writelog(logbuff);
       printf(">order is mkdir\n");
       mkDir_3th(mysql,username,parent_id,owner_id,filename,peerfd);
   }else{
       //日志记录
       char logbuff[100]={0};
       sprintf(logbuff,"order is :erro command! filename is:%s",filename);
       writelog(logbuff);
       char buff[100]="erro command";
       trainSend(buff,peerfd);
   }
return parent_id;

}
//删除文件
int rm( char *dir,int peerfd )
{
    printf("enter rm \n");
    char cur_dir[] = ".";
    char up_dir[] = "..";
    char dir_name[128];
    DIR *dirp;
    struct dirent *dp;
    struct stat dir_stat;

    // 参数传递进来的目录不存在，直接返回
    if ( 0 != access(dir, F_OK)   ) {
        printf("filename error\n");

        char buff[100]="filename error";
        trainSend(buff,peerfd);
        // return 0;
    }

    // 获取目录属性失败，返回错误
    if ( 0 > stat(dir, &dir_stat)   ) {
        char buff[100]="get directory stat error";
        trainSend(buff,peerfd);
    }

    if ( S_ISREG(dir_stat.st_mode)   ) {  // 普通文件直接删除
        remove(dir);
    } else if ( S_ISDIR(dir_stat.st_mode)   ) {   // 目录文件，递归删除目录中内容
        dirp = opendir(dir);
        while ( (dp=readdir(dirp)) != NULL   ) {
            // 忽略 . 和 ..
            if ( (0 == strcmp(cur_dir, dp->d_name)) || (0 == strcmp(up_dir, dp->d_name))   ) {
                continue;
            }

            sprintf(dir_name, "%s/%s", dir, dp->d_name);
            rm(dir_name,peerfd);   // 递归调用
        }
        closedir(dirp);

        rmdir(dir);     // 删除空目录
    } else {
        char buff[100]="unknow file type!";
        trainSend(buff,peerfd);
    }

    char buff[100]="rm is success";
    trainSend(buff,peerfd);
}

void rm_3th(MYSQL*mysql,char*username,char*filename,int parent_id,
            int owner_id,int peerfd){
    char type[5]={0};
    char query[1000]={0};
    char md5[100]={0};

    MYSQL_RES *res;//SQL执行结果
    MYSQL_ROW row ={0};//保存行数据
    int num_fields;//保存列数

    sprintf(query,"select type, md5 from %s where filename = '%s' and parent_id = %d and owner_id = %d;",
            username,filename,parent_id,owner_id);
    printf("rm_3th query is:%s\n",query);
    handlQuery(mysql,query,peerfd);

    res=mysql_store_result(mysql);
    num_fields = mysql_num_fields(res);

    while((row=mysql_fetch_row(res))!=NULL){
        printf("!!enter 1 while\n");
        //char b[5]={0};
        memset(type,0,sizeof(type));
        strcpy(type,row[0]);//把该文件的类型找出来
        //printf("b is:%s\n",b);
        printf("type is:%s\n",type);
        strcpy(md5,row[1]);
        printf("md5 is:%s\n",md5);

        if(memcmp(type,"d",strlen(type))==0){
            mysql_free_result(res);
            memset(query,0,sizeof(query));
            sprintf(query,"select id from %s where filename= '%s' and parent_id = %d and owner_id = %d;",
                    username,filename,parent_id,owner_id);
            printf("rm_3th 1 query:%s\n",query);
            handlQuery(mysql,query,peerfd);
            res=mysql_store_result(mysql);
            num_fields = mysql_num_fields(res);
            int id =0;

            row=mysql_fetch_row(res);
            id = atoi(row[0]);
            printf("rm_3th id:%d\n",id);
            memset(query,0,sizeof(query));
            mysql_free_result(res);

            sprintf(query,"select * from server where parent_id = %d;",id);
            handlQuery(mysql,query,peerfd);

            res=mysql_store_result(mysql);
            if((row=mysql_fetch_row(res))==NULL){//文件夹为空,则删除
                //删除用户虚拟表上信息
                memset(query,0,sizeof(query));
                sprintf(query,"delete from %s where filename= '%s' and parent_id = %d and owner_id = %d;",
                        username,filename,parent_id,owner_id);
                printf("-------rm_3th_dir query:%s\n",query);
                handlQuery(mysql,query,peerfd);
                //删除server虚拟表上信息
                memset(query,0,sizeof(query));
                sprintf(query,"delete from server where filename= '%s' and parent_id = %d and owner_id = %d;",
                        filename,parent_id,owner_id);
                printf("-------rm_3th_dir query:%s\n",query);
                handlQuery(mysql,query,peerfd);
                char a[100]="handl rm is success!";
                trainSend(a,peerfd);
                return;

            }else{//文件夹不为空
                char a[100]="this file is not NULL dirctory ,can not delete!";
                trainSend(a,peerfd);
                return;

            } 
        }else{
            memset(query,0,sizeof(query));
            sprintf(query,"select md5 from server where md5 = '%s';",
                    md5);
            printf("rm_3th query:%s\n",query);
            handlQuery(mysql,query,peerfd);
            res=mysql_store_result(mysql);
            num_fields = mysql_num_fields(res);

            while((row=mysql_fetch_row(res))!=NULL){
                printf("!!enter 2 while\n");

                while((row=mysql_fetch_row(res))!=NULL){//查询结果第二行还有数据则只删除表上的文件数据
                    printf("!!enter 3 while\n");
                    //删除用户虚拟表上信息
                    memset(query,0,sizeof(query));
                    sprintf(query,"delete from %s where md5 = '%s' and parent_id = %d and owner_id = %d;",
                            username,md5,parent_id,owner_id);
                    printf("-------rm_3th query:%s\n",query);
                    handlQuery(mysql,query,peerfd);
                    //删除server虚拟表上信息
                    memset(query,0,sizeof(query));
                    sprintf(query,"delete from server where md5 = '%s' and parent_id = %d and owner_id = %d;",
                            md5,parent_id,owner_id);
                    printf("-------rm_3th query:%s\n",query);
                    handlQuery(mysql,query,peerfd);
                    char a[100]="hanl rm is success!";
                    trainSend(a,peerfd);
                    return;
                }
                //删除用户虚拟表上信息
                memset(query,0,sizeof(query));
                sprintf(query,"delete from %s where md5 = '%s' and parent_id = %d and owner_id = %d;",
                        username,md5,parent_id,owner_id);
                printf("-------rm_3th query:%s\n",query);
                handlQuery(mysql,query,peerfd);
                //删除server虚拟表上信息
                memset(query,0,sizeof(query));
                sprintf(query,"delete from server where md5 = '%s' and parent_id = %d and owner_id = %d;",
                        md5,parent_id,owner_id);
                printf("-------rm_3th query:%s\n",query);
                handlQuery(mysql,query,peerfd);
                char a[100]="hanl rm is success!";
                trainSend(a,peerfd);

                rm(md5,peerfd);
                return;
            }

        }
    }

    //文件名不存在，则返回错误
    char a[100]="this is error failename";
    trainSend(a,peerfd);

}

/*void rm_judge(MYSQL*mysql,char*username,char*filename,
  char*md5,int parent_id,int owner_id,int peerfd){
  MYSQL_RES *res;//SQL执行结果
  MYSQL_ROW row;//保存行数据
  int num_fields;//保存列数
  char query[1000]={0};
  char type[5]={0};
  sprintf(query,"select type from server where filename = '%s' and parent_id = %d, and owner_id = %d;",
  filename,parent_id,owner_id);
  handlQuery(mysql,query);
  res=mysql_store_result(mysql);
  num_fields = mysql_num_fields(res);
  row = mysql_fetch_row(res);
  strcpy(type,row[0]);
  if(memcmp(type,"d",strlen(type))==0){
  char a[100]="this file is dirctory ,can not delete!";
  trainSend(a,peerfd);
  }else{
  memset(query,0,sizeof(query));
  sprintf(query,"select md5 from server where filename = '%s' and parent_id = %d, and owner_id = %d;",
  filename,parent_id,owner_id);
  while((row=mysql_fetch_row(res))!=NULL){
  while((row=mysql_fetch_row(res))!=NULL){//查询结果第二行还有数据则只删除表上的文件数据
  memset(query,0,sizeof(query));
  sprintf(query,"delete from %s where md5 = '%s';",
  username,md5);

  }
  }

  }


  }*/
//创建文件
void mkDir(char *filename,int fd){

    char path[PATH_MLEN];
    getcwd(path, PATH_MLEN);

    printf("mkDir: path = %s\n", path);

    DIR *dir = opendir(path); //打开目录
    ERROR_CHECK(dir, NULL, "opendir");

    struct dirent *pdirent; //目录项指针
    while ((pdirent = readdir(dir)) != NULL)
    {
        if (strcmp(pdirent->d_name, filename) == 0 && pdirent->d_type == DT_DIR) //该文件夹已存在，则创建失败
        {
            char msg[128] = "mkdir faild,this dir has been created.\n";
            trainSend(msg,fd);
            //sendn(fd, msg, strlen(msg));
            //closedir(dir);
            return;
        }

    }

    char filePath[PATH_MLEN] = {0};
    strcpy(filePath, path);
    strcat(filePath, "/");
    strcat(filePath, filename);

    printf("mkDir: filePath = %s\n", filePath);

    int ret = mkdir(filePath, 0777); //创建文件夹
    ERROR_CHECK(ret, -1, "mkdir");

    char msg[128] = "mkdir success.\n";
    trainSend(msg,fd);
    // sendn(fd, msg, strlen(msg));
    closedir(dir);
}

//创建文件
void mkDir_3th(MYSQL*mysql,char*username,int parent_id,int owner_id,char *filename,int fd){

    char query[1000]={0};
    //char path[PATH_MLEN];
    char md5[5]="0";
    int filesize = 0;
    char type[5] = "d";
    int num = 0;

    MYSQL_RES *res;//SQL执行结果
    MYSQL_ROW row;//保存行数据
    int num_fields;//保存列数

    sprintf(query,"select parent_id from %s where filename = '%s';",
            username,filename);
    printf("mkDir query is:%s\n",query);

    handlQuery(mysql,query,fd);
    res = mysql_store_result(mysql);//获取结果
    printf("ls res is success\n");

    num_fields = mysql_num_fields(res);//获取结果列数
    printf("ls num_fields is success\n");
    printf("ls num_fields is:%d\n",num_fields);

    while((row = mysql_fetch_row(res))!=NULL){
        for(int i =0 ;i<num_fields;i++){
            num = atoi(row[i]);
            printf("num is:%d\n",num);
            if(num == parent_id){//该文件存在
                char msg[128] = "mkdir faild,this dir has been created.\n";
                trainSend(msg,fd);

            }else{
                insertTable(mysql,username,parent_id,
                            filename,owner_id,md5,
                            filesize,type,fd); 
                char msg[128] = "mkdir success.\n";
                trainSend(msg,fd);
            }
        }
    }
    insertTable(mysql,username,parent_id,
                filename,owner_id,md5,
                filesize,type,fd); 
    char msg[128] = "mkdir success.\n";
    trainSend(msg,fd);
    mysql_free_result(res);

    //getcwd(path, PATH_MLEN);

    //printf("mkDir: path = %s\n", path);

    //DIR *dir = opendir(path); //打开目录
    //ERROR_CHECK(dir, NULL, "opendir");

    //struct dirent *pdirent; //目录项指针
    //while ((pdirent = readdir(dir)) != NULL)
    //{
    //    if (strcmp(pdirent->d_name, filename) == 0 && pdirent->d_type == DT_DIR) //该文件夹已存在，则创建失败
    //    {
    //        char msg[128] = "mkdir faild,this dir has been created.\n";
    //        trainSend(msg,fd);
    //        insertTable(mysql,username,parent_id,
    //                    filename,owner_id,md5,
    //                    filesize,type); 
    //        //sendn(fd, msg, strlen(msg));
    //        //closedir(dir);
    //        
    //        return;
    //    }

    //}

    //char filePath[PATH_MLEN] = {0};
    //strcpy(filePath, path);
    //strcat(filePath, "/");
    //strcat(filePath, filename);

    //printf("mkDir: filePath = %s\n", filePath);

    //int ret = mkdir(filePath, 0777); //创建文件夹
    //ERROR_CHECK(ret, -1, "mkdir");

    //char msg[128] = "mkdir success.\n";
    //trainSend(msg,fd);
    //insertTable(mysql,username,parent_id,
    //            filename,owner_id,md5,
    //            filesize,type); 
    //// sendn(fd, msg, strlen(msg));
    //closedir(dir);
}
//ls指令实现
void ls(int sockfd){
    int ret;
    char*cwd=getcwd(NULL,0);
    DIR *dirp=opendir(cwd);
    if(dirp==NULL){
        fprintf(stderr,"open dir:%s failed",cwd);

    }
    struct dirent *pDir=NULL;
    while((pDir=readdir(dirp))!=NULL){
        if(strcmp(pDir->d_name,".")==0||strcmp(pDir->d_name,"..")==0){
            continue;

        }
        else {
            //ret=send(sockfd,pDir->d_name,strlen(pDir->d_name),0);
            //ERROR_CHECK(ret,-1,"send");
            trainSend(pDir->d_name,sockfd);

        }

    }
    free(cwd);
    closedir(dirp);
}

//ls虚拟表实现
void ls_3th(MYSQL*mysql,char*username,
            int parent_id,int sockfd){

    char query[1000]={0};
    sprintf(query,"select filename from %s where parent_id = %d",
            username,parent_id);
    printf("ls query is:%s\n",query);

    MYSQL_RES *res;//SQL执行结果
    MYSQL_ROW row;//保存行数据
    int num_fields;//保存列数

    handlQuery(mysql,query,sockfd);
    res = mysql_store_result(mysql);//获取结果
    printf("ls res is success\n");

    num_fields = mysql_num_fields(res);//获取结果列数
    printf("ls num_fields is success\n");
    printf("ls num_fields is:%d\n",num_fields);

    while((row = mysql_fetch_row(res))!=NULL){
        for(int i =0 ;i<num_fields;i++){
            printf("row[%d] is: %s\n",i,row[i]);
            trainSend(row[i],sockfd);
        }
    }
    mysql_free_result(res);
}

//cd命令实现
void cd(char *path ,int sockfd){
    int ret;
    char errbuf[1024]={0};
    char *cwdpath=NULL;

    ret=chdir(path);
    if(-1==ret){
        strerror_r(errno,errbuf,sizeof(errbuf));
        trainSend(errbuf,sockfd);
        /*ret=send(sockfd,errbuf,strlen(errbuf),0);
          ERROR_CHECK(ret,-1,"send");*/
    }
    cwdpath=getcwd(NULL,0);
    if(NULL==cwdpath){
        strerror_r(errno,errbuf,sizeof(errbuf));
        trainSend(errbuf,sockfd);
        /*ret=send(sockfd,errbuf,strlen(errbuf),0);
          ERROR_CHECK(ret,-1,"send");*/
    }
    //发送结果
    trainSend(cwdpath,sockfd);
    /*ret=send(sockfd,cwdpath,strlen(cwdpath),0);
      ERROR_CHECK(ret, -1, "send");*/
}

//使刚进来的用户，当前所在目录为serverFile
void cd1(char *path){
    int ret;
    char errbuf[1024]={0};
    char *cwdpath=NULL;
    ret=chdir(path);
    if(-1==ret){
        strerror_r(errno,errbuf,sizeof(errbuf));
    }
    cwdpath=getcwd(NULL,0);
    if(NULL==cwdpath){
        strerror_r(errno,errbuf,sizeof(errbuf));
    }
}

int cd_3th(MYSQL*mysql,char*username,
           char*filename,int owner_id,
           int parent_id,int peerfd){

    char query[1000]={0};
    char type[10] = {0};

    MYSQL_RES *res;//SQL执行结果
    MYSQL_ROW row;//保存行数据
    int num_fields;//保存列数

    if(memcmp(filename,"..",strlen(filename))==0){
        sprintf(query,"select parent_id from %s where id = %d;",
                username,parent_id);
        handlQuery(mysql,query,peerfd);
        res = mysql_store_result(mysql);//获取结果
        printf("ls res is success\n");

        num_fields = mysql_num_fields(res);//获取结果列数
        printf("ls num_fields is success\n");
        printf("ls num_fields is:%d\n",num_fields);

        while((row = mysql_fetch_row(res))!=NULL){
            parent_id = atoi(row[0]); 
            char a[100]="order cd is success";
            trainSend(a,peerfd);
            return parent_id;
        }

        char a[100]="you are alread in root directory";
        trainSend(a,peerfd);
        return parent_id;
    }else{
        sprintf(query,"select type, id from %s where filename = '%s';",
                username,filename);
        handlQuery(mysql,query,peerfd);

        res = mysql_store_result(mysql);//获取结果
        printf("ls res is success\n");

        num_fields = mysql_num_fields(res);//获取结果列数
        printf("ls num_fields is success\n");
        printf("ls num_fields is:%d\n",num_fields);

        while((row = mysql_fetch_row(res))!=NULL){
            strcpy(type,row[0]);
            if(memcmp(type,"f",strlen(type))==0){
                char a[100]="thie file is not dir";
                trainSend(a,peerfd);
                return parent_id;
            }else{
                parent_id = atoi(row[1]);
                return parent_id;
            }
        }
        char a[100]="filename  is error";
        trainSend(a,peerfd);
        return parent_id;
    }
    return parent_id;
}

//pwd命令实现
void pwd(int sockfd){
    printf("enter pwe\n");
    int ret;
    char cwdpath[512];
    char errbuf[1024]={0};
    getcwd(cwdpath,sizeof(cwdpath));
    printf("%s\n",cwdpath);
    /*if(NULL==cwdpath){
      strerror_r(errno,errbuf,sizeof(errbuf));
      trainSend(errbuf,sockfd);
      ret=send(sockfd,errbuf,strlen(errbuf),0);
      ERROR_CHECK(ret,-1,"send");

      }*/
    trainSend(cwdpath,sockfd);

}

void pwd_3th(MYSQL*mysql,char*username,
             int parent_id,int peerfd){

    int parent_id_1 = 1;
    char fileName[1000]={0};

    if(parent_id == 0){
        char a[100]="serverFile/";
        trainSend(a,peerfd);
    }else{
        while(parent_id_1 !=0){
            MYSQL_RES *res;//SQL执行结果
            MYSQL_ROW row;//保存行数据
            int num_fields;//保存列数
            char query[1000]={0};
            sprintf(query,"select parent_id, filename from %s where id = %d;",
                    username,parent_id);
            handlQuery(mysql,query,peerfd);

            res = mysql_store_result(mysql);//获取结果
            printf("ls res is success\n");

            num_fields = mysql_num_fields(res);//获取结果列数
            printf("ls num_fields is success\n");
            printf("ls num_fields is:%d\n",num_fields);

            while((row = mysql_fetch_row(res))!=NULL){
                parent_id_1 = atoi(row[0]);
                parent_id = parent_id_1; 
                char pwdpass[1000]={0};
                sprintf(pwdpass,"%s/",row[1]);
                printf("pwdpass is:%s\n",pwdpass);
                strcat(pwdpass,fileName);
                printf("pwdpass 2 is:%s\n",pwdpass);
                memcpy(fileName,pwdpass,strlen(pwdpass));


                printf("filename is:%s\n",fileName);

                printf("!!parent_id =%d\n",parent_id);
                printf("!!parent_id_1 =%d\n",parent_id_1);
            }
            //sprintf(pwdpass,"serverFile%s",fileName);

            /*else{
              strcpy(fileName,"serverFile/");
              trainSend(fileName,peerfd);

              }*/
            /*while((row = mysql_fetch_row(res))!=NULL){
              parent_id_1 = atoi(row[0]);
              printf("!!parent_id_1 =%d\n",parent_id_1);
              sprintf(fileName,"serverFile/%s/",row[1]);
              }
              if(row==NULL){
              printf("enter row == NULL\n");
              strcpy(fileName,"pwd is error!");
              trainSend(fileName,peerfd);
              return;
              }
              }*/
            //trainSend(fileName,peerfd);
    }
    char pwdpass[1000]="serverFile/";
    printf("pwdpass 3 is:%s\n",pwdpass);
    strcat(pwdpass,fileName);
    printf("pwdpass 3 is:%s\n",pwdpass);
    memcpy(fileName,pwdpass,strlen(pwdpass));
    trainSend(fileName,peerfd);
}
}
//puts命令实现
void do_puts(int sfd, char *cmd)
{
    printf("do_puts is enter\n");
    train_t train;
    memset(&train, 0, sizeof(train));
    recvn(sfd, &train.length, 4);
    printf("train.len=%d\n", train.length);
    if (train.length == -1)
    {
        printf("puts error\n");
        char buff[100]= "puts error";
        trainSend(buff,sfd);
        return;
    }
    recv_file(sfd, cmd);

}

//puts 虚拟表实现

void do_puts_3th(MYSQL*mysql,char*cmd,char*username,
                 char*md5,int peerfd,int parent_id,
                 int owner_id,int filesize){
    MYSQL_RES *res;//SQL执行结果
    MYSQL_ROW row;//保存行数据
    int num_fields;//保存列数
    char query[1000]={0};
    char type[3]="f";
    sprintf(query,"select md5 from server where md5 = '%s';",
            md5);
    handlQuery(mysql,query,peerfd);
    res = mysql_store_result(mysql);//获取结果
    printf("ls res is success\n");

    num_fields = mysql_num_fields(res);//获取结果列数
    printf("ls num_fields is success\n");
    printf("do_puts is enter\n");


    //判断server端是否存在这个文件
    while((row = mysql_fetch_row(res))==NULL){//不存在
        char c[10]="1";
        trainSend(c,peerfd);

        train_t train;
        memset(&train, 0, sizeof(train));
        recvn(peerfd, &train.length, 4);
        printf("train.len=%d\n", train.length);
        if (train.length == -1)
        {
            printf("puts error\n");
            char buff[100]= "puts error";
            trainSend(buff,peerfd);
            return;
        }

        int ret =recv_file(peerfd, md5);
        if(ret == 1){
            return;
        }else{
            insertTable(mysql,username,parent_id,
                        cmd,owner_id,md5,filesize,
                        type,peerfd);
            return ;
        }
    }
    char c[10]="0";
    printf("puts c is:%s\n",c);
    trainSend(c,peerfd);
    insertTable(mysql,username,parent_id,
                cmd,owner_id,md5,filesize,
                type,peerfd);
}

int recv_file(int sfd, char *filename)
{
    train_t train;
    memset(&train, 0, sizeof(train));
    printf("start recv_file\n");
    int fd = open(filename, O_CREAT | O_RDWR | O_APPEND, 0666);
    if (fd == -1)
    {
        printf("open error\n");
        char buff[100]="open error";
        trainSend(buff,sfd);
        return 1;

    }
    memset(&train, 0, sizeof(train));
    off_t filesize;
    recvn(sfd, &train.length ,sizeof(train.length));
    recvn(sfd, &filesize, train.length);
    int left = filesize, cur = 0, ret = 0;
    while (left > 0)
    {
        memset(&train, 0, sizeof(train));
        recvn(sfd, &train.length, 4);
        recvn(sfd, train.data, train.length);
        ret = write(fd, train.data, train.length);
        if (ret == -1)
        {
            printf("write error");
            char buff[100]="write error";
            trainSend(buff,sfd);
            return 1;

        }
        cur += ret;
        left -= ret;
        printf("letf is %d\n",left);

    }
    char sbuff[100]="recv file success";
    trainSend(sbuff,sfd);
    return 0;
}

//gets 命令实现
void do_gets(int sfd, char *cmd)
{
    send_file(sfd, cmd);

}

void do_gets_3th(MYSQL*mysql,char*username,char*filename,
                 int parent_id,int owner_id,int peerfd){
    MYSQL_RES *res;//SQL执行结果
    MYSQL_ROW row;//保存行数据
    int num_fields;//保存列数
    char query[1000]={0};
    char md5[100]={0};
    sprintf(query,"select md5 from %s where filename = '%s' and parent_id = %d and owner_id = %d;",
            username,filename,parent_id,owner_id);
    handlQuery(mysql,query,peerfd);
    res = mysql_store_result(mysql);//获取结果
    printf("ls res is success\n");

    num_fields = mysql_num_fields(res);//获取结果列数
    printf("ls num_fields is success\n");
    printf("ls num_fields is:%d\n",num_fields);

    printf("do_puts is enter\n");


    //判断server端是否存在这个文件
    while((row = mysql_fetch_row(res))!=NULL){
        strcpy(md5,row[0]);
        printf("gets md5:%s\n",md5);

        /*char a[5]={0};
          trainRecv(a,peerfd);
          printf("puts a is:%s\n",a);
          if(memcmp(a,"5",strlen(a))==0){
          return;
          }else{
          send_file(peerfd,md5);
          return ;
          }*/
        send_file(peerfd,md5);
        return;
    }

    /*char a[5]={0};
      trainRecv(a,peerfd);
      printf("puts a is:%s\n",a);*/

    //不存在
    train_t train;
    train.length = -1;
    sendn(peerfd, &train, 4);

}

void send_file(int sfd, char *filename)
{
    //先判断文件是否存在
    off_t file_exit = 0;
    train_t train;
    memset(&train, 0, sizeof(train_t));
    // recvn(sfd, &train.len, 4);
    //  recvn(sfd, &file_exit, train.len);
    //  printf("file_exit=%ld\n", file_exit);

    memset(&train, 0, sizeof(train_t));
    printf("---filename strlen %ld\n",strlen(filename));
    int fd = open(filename, O_RDONLY);
    if (fd == -1)
    {
        printf("puts error\n"); //本地不存在此文件
        train.length = -1;
        sendn(sfd, &train, 4);
        return;
    }
    train.length = 1;
    sendn(sfd, &train, 4);

    struct stat file_status;
    memset(&file_status, 0, sizeof(file_status));
    fstat(fd, &file_status);
    off_t file_size = file_status.st_size - file_exit;
    memset(&train, 0, sizeof(train));
    memcpy(train.data, &file_size, sizeof(file_size));
    train.length = sizeof(file_size);
    sendn(sfd, &train, train.length + 4);

    int ret, left = file_size, cur = 0;
    while (left > 0)
    {
        memset(&train, 0, sizeof(train));
        ret = read(fd, train.data, sizeof(train.data));
        if (ret == 0)
        {
            printf("read error\n");
            return;
        }
        train.length = ret;
        ret = sendn(sfd, &train, 4 + train.length);
        cur += train.length;
        left -= train.length;
    }
    printf("send_file send file success\n");
}



